package in.muton.wicket.extensions.upload;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.extensions.ajax.markup.html.form.upload.UploadInfo;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.util.lang.Bytes;
import org.apache.wicket.util.upload.FileUploadException;

import com.edushare.common.exceptions.EduShareRuntimeException;

public class UploadProcessWebRequest extends ServletWebRequest{

	private static Log log = LogFactory.getLog(UploadProcessWebRequest.class);
	final HttpServletRequest req;
	private static final String SESSION_KEY = UploadProcessWebRequest.class.getName();
	
	/** constructor from superclass */
	public UploadProcessWebRequest(final HttpServletRequest req) {
		super(req);
		this.req = req;
	}
	
	@Override
	public WebRequest newMultipartWebRequest(Bytes maxsize) {
		try {
			return new MultipartRequest(req, maxsize);
		} catch (FileUploadException e) {
			log.error("Error creating Mutipart Request.", e);
//			throw new EduShareRuntimeException("Multipart request Exception", e); //does not work
			throw new WicketRuntimeException(e);
		}
//		return super.newMultipartWebRequest(maxsize);
	}

	public static void setUploadInfo(HttpServletRequest request, UploadInfo uploadInfo){
		if(request == null)
			throw new IllegalArgumentException("HttpServletRequest, request, can't be null.");
		if(uploadInfo == null)
			throw new IllegalArgumentException("Upload info can't be set as NULL.");
		/*
		 * if upload info is processing started
		 */
		
		request.getSession().setAttribute(SESSION_KEY, uploadInfo);
	}
	
	public static UploadInfo getUploadInfo(HttpServletRequest request) {
		if(request == null)
			throw new IllegalArgumentException("HttpServletRequest, request, can't be null.");
		return (UploadInfo)request.getSession().getAttribute(SESSION_KEY);
	}
	
	public static void clearUploadInfo(HttpServletRequest request){
		if(request == null)
			throw new IllegalArgumentException("HttpServletRequest, request, can't be null.");
		request.getSession().removeAttribute(SESSION_KEY);
	}
}
